package com.dimples.dd.auth.core.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.dimples.dd.common.enums.UserTypeEnum;
import com.dimples.dd.common.model.DDAuthUser;
import com.dimples.dd.common.util.monitor.TracerUtils;
import com.dimples.dd.common.util.servlet.ServletUtils;
import com.dimples.dd.ip.core.utils.IPUtils;
import com.dimples.dd.system.api.logger.LoginLogFeign;
import com.dimples.dd.system.api.logger.dto.LoginLogCreateReqDTO;
import com.dimples.dd.system.api.user.UserFeignClient;
import com.dimples.dd.system.enums.logger.LoginLogTypeEnum;
import com.dimples.dd.system.enums.logger.LoginResultEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 登录日志工具类
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/9/3
 */
@Slf4j
public class LoginLogUtil {

    public static void createLoginLog(String username, LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult, UserTypeEnum userType) {
        DDAuthUser userAuthInfo = SpringUtil.getBean(UserFeignClient.class).getUserAuthUser(username);
        // 插入登录日志
        LoginLogCreateReqDTO reqDTO = new LoginLogCreateReqDTO();
        reqDTO.setLogType(logTypeEnum.getType());
        reqDTO.setTraceId(TracerUtils.getTraceId());
        reqDTO.setUserId(userAuthInfo.getUserId());
        reqDTO.setUserType(userType.getValue().byteValue());
        reqDTO.setUsername(username);
        reqDTO.setBrowser(ServletUtils.getBrowser());
        reqDTO.setOs(ServletUtils.getOs());

        try {
            String address = IPUtils.getFormatArea(ServletUtils.getIp());
            reqDTO.setLoginLocation(address);
            reqDTO.setUserIp(ServletUtils.getIp());
        } catch (Exception e) {
            log.error("记录登录日志获取IP和地址信息异常: {}", ExceptionUtil.stacktraceToString(e));
        }

        reqDTO.setResult(loginResult.getResult().byteValue());

        // 异步存储登录日志
        ThreadUtil.execAsync(
                () -> {
                    // 因为异步线程需要新的线程，而新的线程里没有request数据，所以我们自己设置进去
//                    RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);


                    SpringUtil.getBean(LoginLogFeign.class).createLoginLog(reqDTO);
                    // 更新最后登录时间
                    if (userAuthInfo.getUserId() != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
                        SpringUtil.getBean(UserFeignClient.class).updateUserLogin(userAuthInfo.getUserId(), ServletUtils.getIp());
                    }
                }, true
        );
    }

}
